package com.weiz.es.controller;

import com.weiz.es.entity.Book;
import com.weiz.es.entity.BookQuery;
import com.weiz.es.util.JSONResult;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;

@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 查询信息
     * @param
     * @return
     */
    @PostMapping(value = "/book/query")
    public JSONResult query(@RequestBody BookQuery bookQuery){
        Query query= getQueryBuilder(bookQuery);
        SearchHits<Book> searchHits = elasticsearchRestTemplate.search(query, Book.class);
        List<SearchHit<Book>> result = searchHits.getSearchHits();
        return JSONResult.ok(result);
    }

    public Query getQueryBuilder(BookQuery query) {
               BoolQueryBuilder builder = boolQuery();
        // 匹配器 模糊查询部分，分析器使用ik (ik_max_word)
        List<QueryBuilder> must = builder.must();

        if (query.getBookName()!=null && !query.getBookName().isEmpty())
            must.add(wildcardQuery("bookName", "*" +query.getBookName()+ "*"));

        if (query.getCategory()!=null && !query.getCategory().isEmpty())
            must.add(wildcardQuery("category", "*" +query.getCategory()+ "*"));

        if (query.getAuthor()!=null && !query.getAuthor().isEmpty())
            must.add(wildcardQuery("author", "*" +query.getAuthor()+ "*"));

        // 筛选器 精确查询部分
        List<QueryBuilder> filter = builder.filter();
        // 范围查询
        if (query.getPriceMin()>0 && query.getPriceMax()>0) {
            RangeQueryBuilder price = rangeQuery("price").gte(query.getPriceMin()).lte(query.getPriceMax());
            filter.add(price);
        }
        // 范围查询
        if (query.getPageMin()>0 && query.getPageMax()>0) {
            RangeQueryBuilder page = rangeQuery("page").gte(query.getPageMin()).lte(query.getPageMax());
            filter.add(page);
        }

        // 分页
        PageRequest pageable = PageRequest.of(query.getPage() - 1, query.getLimit());
        // 排序
        SortBuilder sort = SortBuilders.fieldSort("price").order(SortOrder.DESC);

        //设置高亮效果
        String preTag = "<font color='#dd4b39'>";//google的色值
        String postTag = "</font>";
        HighlightBuilder.Field highlightFields = new HighlightBuilder.Field("category").preTags(preTag).postTags(postTag);

        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(builder)
                .withHighlightFields(highlightFields)
                .withPageable(pageable)
                .withSort(sort)
                .build();
        return searchQuery;
    }
}
